package model

import (
	"fmt"
	"novel-mgr1/app"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var err error
var DB *gorm.DB

func Init() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	Mysql := app.App.Mysql
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", Mysql.User, Mysql.Password, Mysql.Host, Mysql.Port, Mysql.Dbname)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("连接成功")
	DB.AutoMigrate(
		&User{},
		&Books{},
		&Novel{},
		&Comment{},
	)
	fmt.Println("迁移成功")
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
